package leetcode.cn;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @version 1.8
 * @Author Djx_hmbb
 * @Date 2023/11/6 20:55
 * @注释:力扣18.四数之和
 */
public class TheSumOfFourNum {
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> lists = new ArrayList<>();
        Arrays.sort(nums);
        if (nums[0] > 0 && target < 0 || nums[nums.length - 1] < 0 && target > 0) return lists;
        for (int i = 0; i < nums.length; ) {
            for (int j = i + 1; j < nums.length; ) {
                int c = j + 1, d = nums.length - 1;
                long  t = (long)target - nums[i] - nums[j];
                System.out.println(t);
                //对c,d区间进行查找,去重
                while (c < d) {
                    if (nums[c] + nums[d] < t) c++;
                    else if (nums[c] + nums[d] > t) d--;
                    else {
                        lists.add(Arrays.asList(nums[i], nums[j], nums[c], nums[d]));
                        c++;
                        d--;
                        while (c < d && nums[c] == nums[c - 1]) c++;
                        while (c < d && nums[d] == nums[d + 1]) d--;
                    }
                }
                //对[j]进行去重
                j++;
                while (j < nums.length && nums[j] == nums[j - 1]) j++;
            }
            //对[i]进行去重
            i++;
            while (i < nums.length && nums[i] == nums[i - 1]) i++;
        }
        return lists;
    }

    public static void main(String[] args) {
        int[] nums = {-1000000000,-1000000000,1000000000,-1000000000,-1000000000};
        int t = 294967296;
        List<List<Integer>> lists = fourSum(nums, t);
        for (List<Integer> i :
                lists) {
            System.out.println(i);
        }
    }
}
